//
//  JsonEngine.m
//  TestARC
//
//  Created by Rayco on 12-10-17.
//  Copyright (c) 2012年 Test. All rights reserved.
//

#import "AppsJsonEngine.h"
#import "JSON.h"
#import "apps123_util.h"

static AppsJsonEngine *engine;
@implementation AppsJsonEngine

#pragma mark - Public

+ (id)sharedEngine {
    if(!engine){
        engine = [[self alloc] init];
    }
    return engine;
}

+ (id)sharedEngine:(NSString *)host {
    if(!engine){
        engine = [[self alloc] initWithHostName:host customHeaderFields:nil];
    }
    return engine;
}

- (void)submitRequest:(NSString *)url params:(NSMutableDictionary *)paramsDic onCompletion:(JsonEngineBlock)completionBlock onError:(MKNKErrorBlock)errorBlock method:(NSString *)method {
    
    [paramsDic setValue:@"apps123callback" forKey:@"jsoncallback"];
    MKNetworkOperation *op = [self operationWithPath:url params:paramsDic httpMethod:method];
    if (!op) {
        return;
    }
    [op onCompletion:^(MKNetworkOperation *completedOperation) {
        
        NSString *responseString = [completedOperation responseString];
//        NSLog(@"responseString : %@",responseString);
        responseString = [apps123_util removeJsonCallback:responseString];
        completionBlock([self toValue:responseString]);
    
    } onError:^(NSError *error) {

        errorBlock(error);
    }];
    
    [self emptyCache];
    [self enqueueOperation:op];
}

- (void)submitRequest:(NSString *)url params:(NSMutableDictionary *)paramsDic onCompletion:(JsonEngineBlock)completionBlock onError:(MKNKErrorBlock)errorBlock method:(NSString *)method emptyCache:(BOOL)emptyCache {
    [paramsDic setValue:@"apps123callback" forKey:@"jsoncallback"];
    MKNetworkOperation *op = [self operationWithPath:url params:paramsDic httpMethod:method];
    if (!op) {
        return;
    }
    [op onCompletion:^(MKNetworkOperation *completedOperation) {
        
        NSString *responseString = [completedOperation responseString];
        //        NSLog(@"responseString : %@",responseString);
        responseString = [apps123_util removeJsonCallback:responseString];
        completionBlock([self toValue:responseString]);
        
    } onError:^(NSError *error) {
        
        errorBlock(error);
    }];
    
    if(emptyCache){
        [self emptyCache];
    }
    [self enqueueOperation:op];
}

- (NSDictionary *)toValue:(NSString *)json {
    return [json JSONValue];
}

@end
